<template>
  <lb-layout
    v-loading="$store.getters.loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="#a19f9fb0;"
    :paddBottom="5"
  >
    <el-row>
      <el-button size="small" @click="goBack"> 返回 </el-button>
      <el-button type="warning" size="small" plain @click="exportDeal"
        >导出</el-button
      >
    </el-row>
    <el-tabs
      ref="tabs"
      v-model="activeName"
      class="text-tabs TTB-no-gutter TTB-gutter"
      @tab-click="handlerTabschange"
    >
      <el-tab-pane label="基1表详情" name="basic1"> </el-tab-pane>
      <el-tab-pane label="基2表全年信息" name="basic2"> </el-tab-pane>
      <el-tab-pane label="基3表全年信息" name="basic3"> </el-tab-pane>
      <el-tab-pane label="基4表全年信息" name="basic4"> </el-tab-pane>
    </el-tabs>
    <basic1 v-show="activeName == 'basic1'" ref="basic1"></basic1>
    <basic2 v-show="activeName == 'basic2'" ref="basic2"></basic2>
    <basic3 v-show="activeName == 'basic3'" ref="basic3"></basic3>
    <basic4 v-show="activeName == 'basic4'" ref="basic4"></basic4>
  </lb-layout>
</template>

  <script>
import {
  postLedger,
  putLedger,
  getLedgerDetail,
  getLedgerlastmonth,
  getLedgerlastyear,
  reportLedger,
  collectLedgerself,
} from "@/api/standingbook/newstandingbook.js";
import { exportBasicBackstageExcel, exportBasicExcel } from "@/utils/xlsx";
import { getInfo } from "@/api/login";
import basic1 from "@/views/work/accounts/newadd/components/basic1.vue";
import basic2 from "@/views/work/accounts/newadd/components/allbasic2.vue";
import basic3 from "@/views/work/accounts/newadd/components/allbasic3.vue";
import basic4 from "@/views/work/accounts/newadd/components/allbasic4.vue";
import { MessageBox } from "element-ui";
export default {
  components: {
    basic1,
    basic2,
    basic3,
    basic4,
  },
  props: {},
  data() {
    return {
      deptLevel: null,
      dataScopeOptions: [
        {
          value: "0",
          label: "月报",
        },
        {
          value: "1",
          label: "季报",
        },
        {
          value: "2",
          label: "半年报",
        },
      ],
      activeName: "basic2",
      disabledFlage: false,
      isCorrect: false,
      apsForm: {
        formRef: "searchform",
        labelWidth: "auto",
        formData: {},
        formConfig: {
          formAttr: {
            inline: true,
            size: "small",
          },
          properties: {
            year: {
              label: "年份:",
              typeName: "el-date-picker",
              type: "year",
              size: "small",
              "value-format": "yyyy",
              placeholder: "请选择年份",
              change: this.handlerSearchDetail,
              "picker-options": {
                disabledDate(time) {
                  let date = new Date();
                  return time.getFullYear() > date.getFullYear();
                },
              },
            },
            periodType: {
              label: "权限范围",
              typeName: "el-select",
              render: (h) => {
                let that = this;
                let arr = [];
                arr = [...that.dataScopeOptions];
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.apsForm?.getFieldsValue().periodType;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择时段类型",
                        value: valNum,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.apsForm?.setFieldValue(
                            "periodType ",
                            value
                          );
                          that.handlerSearchDetail();
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            companyName: {
              label: "单位名称:",
              typeName: "el-input",
              disabled: true,
            },
          },
        },
      },
      buttonName: "",
    };
  },
  created() {
    this.getDeptLevel();
    // setTimeout(() => {
    //   this.searchFromSet();
    // }, 200);
  },
  methods: {
    handlerSearchDetail() {
      console.log(11);
    },
    exportDeal() {
      let user = this.$store.state.user;
      let deptName = user?.deptName ?? "未知单位名称";
      let infos = [];
      infos.push(deptName);
      infos.push(this.$refs["basic1"].info?.headOfUnitName ?? "");
      infos.push(this.$refs["basic1"].info?.statisticsPersonName ?? "");
      infos.push(this.$refs["basic1"].info?.createTime ?? "");
      let text =
        this.activeName == "basic1"
          ? "公共机构基本信息"
          : this.activeName == "basic2"
          ? "公共机构能源资源消费状况"
          : this.activeName == "basic3"
          ? "公共机构数据中心机房能源消费状况"
          : "公共机构采暖能源资源消费状况";
      let index =
        this.activeName == "basic1"
          ? 1
          : this.activeName == "basic2"
          ? 2
          : this.activeName == "basic3"
          ? 3
          : 4;
      let fileName = text + "-" + deptName;
      let cols = [{ wpx: 240 }];
      let ref = this.$refs[this.activeName].$refs.excelTable;
      //exportExcel(ref, fileName, cols);
      if (1 == index) {
        //基1表后台下载
        exportBasicBackstageExcel(fileName, user?.deptId);
      } else {
        infos.push(this.$refs[this.activeName].form.year);
        let name =
          this.$refs[this.activeName].form.periodType == 0
            ? "月报"
            : this.$refs[this.activeName].form.periodType == 1
            ? "季报"
            : this.$refs[this.activeName].form.periodType == 2
            ? "半年报"
            : "-";
        // infos.push(this.$refs["searchform"].getFieldsValue().yearmonth);
        infos.push(name);
        //其他表前端下载
        exportBasicExcel(ref, fileName, cols, index, infos);
      }
    },
    async getDeptLevel() {
      const res = await getInfo();
      this.deptLevel = res.user.deptLevel;
      // 纠正
      let query = this.$route.query;
      if (query.correct == "1") {
        this.isCorrect = true;
        if (this.deptLevel == 0) {
          this.buttonName = "纠正并上报";
        } else {
          this.buttonName = "纠正并汇总";
        }
      } else {
        this.isCorrect = false;
        if (this.deptLevel == 0) {
          this.buttonName = "保存并上报";
        } else {
          this.buttonName = "保存并汇总";
        }
      }
    },
    searchFromSet() {
      let query = this.$route.query;
      let disabled = query.disabled;
      if (disabled == "0") {
        this.disabledFlage = false;
      }
      if (disabled == "1") {
        this.disabledFlage = true;
      }
      let year = query.year;
      let month = query.month;
      this.$refs?.searchform?.setFieldValue("yearmonth", year + month);
      let user = this.$store.state.user;
      let deptName = user?.deptName ?? "未知单位名称";
      this.$refs?.searchform?.setFieldValue("companyName", deptName);
      this.$refs?.searchform?.setFieldValue("fillType", "月报");
    },
    handlerTabschange() {
      const name = this.$refs.tabs.value;
      if (this.activeName === name) {
        return false;
      }
    },
    goBack() {
      // this.$router.push({
      //   path: "/work/standbook/newadd",
      // });
      this.$router.go(-1);
      // let activeMenu = this.$route.meta.activeMenu; // 激活的菜单也是返回的菜单
      // this.$router.push({
      //   path: activeMenu,
      // });
    },
    handlerSubmit(type) {
      let list = [
        ...this.$refs.basic2.listform.list,
        ...this.$refs.basic3.listform.list,
        ...this.$refs.basic4.listform.list,
      ];
      let deptId = this.$store.state.user.deptId;
      let query = this.$route.query;
      let year = query.year;
      let month = query.month;
      let params = {};
      params.deptId = deptId;
      params.year = year;
      params.month = month;
      list.map((item) => {
        let key = item.fields;
        if (!item.notInput) {
          params[key] = item.value;
        }
      });
      if (type == 1) {
        this.$modal
          .confirm("确认保存" + year + month + "的台账吗？")
          .then(() => {
            this.requestSave(params, type);
          })
          .catch(() => {
            this.$message({
              message: "取消保存",
            });
          });
      } else {
        let moName = "";
        if (this.deptLevel == 0) {
          moName = "上报";
        } else if (this.deptLevel == 1 || this.deptLevel == 2) {
          moName = "汇总";
        }
        this.$modal
          .confirm("确认保存并" + moName + year + month + "的台账吗？")
          .then(() => {
            this.requestSave(params, type);
          })
          .catch(() => {
            this.$message({
              message: "取消保存并" + moName,
            });
          });
      }
    },
    requestSave(params, falge) {
      let query = this.$route.query;
      if (query.id && String(query.id).length > 0) {
        // 修改
        params.id = query.id;
        this.edit(params, falge);
      } else {
        // 新增
        this.add(params, falge);
      }
    },
    add(params, falge) {
      postLedger(params)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          let id = res?.data;
          if (falge == 1) {
            this.$message.success("保存成功");
            setTimeout(() => {
              this.$router.push({ path: "/work/standbook/newadd" });
            }, 200);
          } else {
            this.collectOrrequest(id);
          }
        })
        .catch(() => {
          // this.$message.error("系统错误,请联系管理员!");
        });
    },
    edit(params, falge) {
      putLedger(params)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          if (falge == 1) {
            this.$message.success("修改成功");
            setTimeout(() => {
              this.$router.push({ path: "/work/standbook/newadd" });
            }, 200);
          } else {
            this.collectOrrequest(this.$route.query.id);
          }
        })
        .catch(() => {
          // this.$message.error("系统错误,请联系管理员!");
        });
    },
    // 上报or汇总
    collectOrrequest(id) {
      let params = {
        ledgerIds: [],
      };
      params.ledgerIds.push(id);
      if (this.deptLevel == 0) {
        // "上报";
        this.requestReport(params);
      } else if (this.deptLevel == 1 || this.deptLevel == 2) {
        // "汇总";
        this.requestCollect(params);
      }
    },
    //上报请求
    requestReport(params) {
      reportLedger(params)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.$message.success("已保存并上报!");
          setTimeout(() => {
            this.$router.push({ path: "/work/standbook/newadd" });
          }, 200);
        })
        .catch(() => {
          // this.$message.error("系统错误,请联系管理员!");
        });
    },
    // 汇总请求
    requestCollect(params) {
      collectLedgerself(params)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.$message.success("已保存并汇总!");
          setTimeout(() => {
            this.$router.push({ path: "/work/standbook/newadd" });
          }, 200);
        })
        .catch(() => {
          // this.$message.error("系统错误,请联系管理员!");
        });
    },
  },
};
</script>

  <style lang="scss" scoped>
.text-tabs {
  margin-left: -40px;
}
.top-button-area {
  display: flex;
  justify-content: flex-end;
}
</style>
